package com.hang.ad.mysql;

import com.alibaba.fastjson.JSON;
import com.hang.ad.mysql.constant.OpType;
import com.hang.ad.mysql.dto.ParseTemplate;
import com.hang.ad.mysql.dto.TableTemplate;
import com.hang.ad.mysql.dto.Template;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class TemplateHolder {
    private ParseTemplate template;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private String SQL = "select table_schema, table_name, " +
            "colunm_name, ordinal_position from information_schema.columns " +
            "where table_schema = ? and table_name = ?";

    @PostConstruct
    private void init(){
        loadJson("template.json");
    }

    public TableTemplate getTable(String tableName){
        return template.getTableTemplateMap().get(tableName);
    }

    private void loadJson(String path){
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream(path);
        try{
            Template template = JSON.parseObject(
                    is, Charset.defaultCharset(), Template.class
            );
            this.template = ParseTemplate.parse(template);
            loadMeta();
        }catch (IOException e){
            log.error(e.getMessage());
            throw new RuntimeException("fail to parse template.json");
        }
    }

    private void loadMeta(){
        for (Map.Entry<String, TableTemplate> entry : template.getTableTemplateMap().entrySet()) {
            TableTemplate table = entry.getValue();
            List<String> updateList = table.getOpTypeFieldSetMap().get(OpType.UPDATE);
            List<String> insertList = table.getOpTypeFieldSetMap().get(OpType.ADD);
            List<String> deleteList = table.getOpTypeFieldSetMap().get(OpType.DELETE);

            jdbcTemplate.query(SQL, new Object[]{
                    template.getDatabase(), table.getTableName()
            }, (rs, i) -> {
                int pos = rs.getInt("ORDINAL_POSITION");
                String colName = rs.getString("COLUMN_NAME");

                if ((updateList != null && updateList.contains(colName)) || (insertList != null && insertList.contains(colName))
                        || (deleteList != null && deleteList.contains(colName))){
                    table.getPosMap().put(pos -1 , colName);
                }
                return null;
            });
        }
    }

}
